﻿Shader "Example02/08菲尼尔着色器"
{
    Properties
    {
        _MainColor("MainColor",Color) =(1,1,1,1)
        _MainTex ("Texture", 2D) = "white" {}
        _FresnelColor("FresnelColor",Color) =(1,1,1,1)
        _Scale("Scale",Range(0,1)) =1
        _Value("Value",Range(0,5)) =2.5
    }
    SubShader
    {
        Tags {
            "RenderType"="Opaque"
            "LightMode"="ForwardBase"
        }
        Pass
        {
            CGPROGRAM
            #pragma vertex vert
            #pragma fragment frag
            #include "UnityCG.cginc"
            #include "Lighting.cginc"
            struct v2f
            {
                float4 vertex : SV_POSITION;
                float3 worldPos : TEXCOORD0;
                float2 texcoord : TEXCOORD1;
                fixed3 normal : NORMAL;
            };

            fixed4 _MainColor;
            sampler2D _MainTex;
            float4 _MainTex_ST;
            fixed4 _FresnelColor;
            float _Scale;
            float _Value;

            v2f vert (appdata_base v)
            {
                v2f o;
                o.vertex = UnityObjectToClipPos(v.vertex);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex);
                o.texcoord =TRANSFORM_TEX(v.texcoord,_MainTex);
                o.normal = v.normal;
                return o;
            }
            fixed4 frag (v2f i) : SV_Target
            {
                // 固定的
                fixed3 worldNormal = normalize(UnityObjectToWorldNormal(i.normal)); // 法线 => 世界坐标
                fixed3 viewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));     // 视角向量
                
                fixed3 col = tex2D(_MainTex, i.texcoord);

                //--- 菲尼尔公式 ------------------------------
                //1 - 法线·视角
                float fresnel = pow(1 - dot(worldNormal, viewDir), _Value) * _Scale;

                col.rgb *= _MainColor + _FresnelColor * fresnel;   // 混合计算
                return  fixed4(col,1);
            }
            ENDCG
        }
    }
}